import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable } from "@ant-design/pro-components";
import { Button, Col, Image, message, Modal, Row, Space, Tabs, TabsProps, Tag } from "antd";
import { useEffect, useRef, useState } from "react";
import { getSelection } from "@/services/selections";
import QueryMaterial2 from "@/components/QueryMaterial2";
import moment from "moment";
import QueryUserDefine from "@/components/QueryUserDefine";
import { s_getPurchaseInfo, s_getTableInfo, s_getTableInfoDetail, s_operateInfo, s_purchase_updateInfo, s_updateInfo, state2text, status2text } from "@/services/basis";
import Addition from "@/components/Addition";

const App:React.FC=()=>{
    const [etype,setEtype]=useState(1);
    const [open,setOpen]=useState(false);
    const [selectedRecord,setSelectedRecord]=useState<DataType[]>([]);
    const [selectDetail,setSelectedDetail]=useState<any[]>([]);
    const [material,setMaterial]=useState([]);
    const [dataSource,setDataSource]=useState<any[]>([]);
    const [userdefine,setUserDefine]=useState<{uid:any,uname:any,vlabel:any,value:any}[]>([]);
    const [rowno,setRowno]=useState(0); 
    const [addition,setAddition]=useState([]);
    const [vouchCode,setVouchCode]=useState(null);

    const mform_ref=useRef<ProFormInstance>();
    const mtable_ref=useRef<ActionType>();
    const mtable2_ref=useRef<ActionType>();
    const editorFormRef=useRef<EditableFormInstance>();

    const [openAlloc,setOpenAlloc]=useState(false);
    const formRef_alloc=useRef<ProFormInstance>();
    const editable_allocMain=useRef<EditableFormInstance>();
    const editable_allocDetail=useRef<EditableFormInstance>();
    const [atype,setAtype]=useState(1);//分配主子件，默认1主件，2子件
    const action_allocMain=useRef<ActionType>();
    const action_allocDetail=useRef<ActionType>();

    interface DataType{
        // mid,id,x_id,org_id,custom_id,operate_time,operater_id,saletype_id,
        // code,state,status,memo,source_type,source_id,addition,business_id,
        // 		material_id,userdefine,userdefine2,quantity,price,taxrate,total,netprice,nettotal,
        // 		source_type2,source_id2,state2,status2,memo2,deliverdate2,
        // 		material_addition,material_code,material_name,scode,invstd,invstd2,
        // 		brand,munit_name,custom_name,org_name,operater_name,business_name,saletype_name
        mid?:number,id?:number,x_id?:number,org_id?:number,custom_id?:number,operate_time?:string,
        operater_id?:number,saletype_id?:number,code?:string,state?:number,status?:number,
        memo?:string,source_type?:string,source_id?:number,addition?:string,business_id?:number,
        material_id?:number,userdefine_id?:string,userdefine_name?:string,quantity?:number,taxrate?:number,
        total?:number,netprice?:number,nettotal?:number,source_type2?:string,source_id2?:number,
        state2?:number,status2?:number,memo2?:string,deliverdate2?:string,material_addition?:string,
        material_code?:string,material_name?:string,scode?:string,invstd?:string,invstd2?:string,
        brand?:string,munit_name?:string,custom_name?:string,org_name?:string,operater_name?:string,
        business_name?:string,saletype_name?:string,
        isalloc?:number,alloc_operate_time?:string,
    }

    const columns:ProColumns<DataType>[]=[
        {dataIndex:'id',title:'ID'},{dataIndex:'custom_name',title:'店铺'},
        {dataIndex:'business_name',title:'业务员'},
        {dataIndex:'code',title:'单据编码'},
        // {dataIndex:'deliverdate',title:'交货日期'},
        {dataIndex:'memo',title:'备注'},{dataIndex:'operater_name',title:'制单人'},
        {dataIndex:'operate_time',title:'制单时间',valueType:'date'},
        {dataIndex:'source_type',title:'申报单来源'},
        {dataIndex:'isalloc',title:'是否已分配',
            render:(text)=><Tag color={text==1?'':'red'} style={{width:80}}>{text==1?'是':'否'}</Tag>
        },
        {dataIndex:'alloc_operate_time',title:'分配时间',valueType:'date',},
        // {dataIndex:'state',title:'进度',
        //   render:(text:any)=>state2text(1,text),
        // },
        // {dataIndex:'status',title:'状态',
        //   render:(text:any)=>status2text(text)
        // },
    ];

    interface DataType2{
        rid?:number,id:number,material_id?:number,material_code?:string,material_name?:string,
        invstd?:string,invstd2?:string,userdefine_id?:string,userdefine_name?:string,munit_name?:string,
        quantity?:number,taxrate?:number,total?:number,netprice?:number,nettotal?:number,price:number,
        deliverdate2?:string,state2?:number,status2?:number,memo2?:string,material_addition?:string,
        pic?:string,alloc_type?:number,default_type?:number,
    }

    const columns2:ProColumns<DataType2>[]=[
        {dataIndex:'rid',title:'RID',editable:false,hidden:true,},
        {dataIndex:'id',title:'ID',editable:false,hidden:true,},
        {dataIndex:'material_id',title:'物料ID',editable:false,hidden:true,},
        {dataIndex:'pic',title:'图片' ,editable:false,
           render:(text)=>{
               var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
               return <Image src={pic}  
                      style={{width:100,height:100}} alt='无' />
          },
        },
        {dataIndex:'material_code',title:'SKU编码',editable:false,},
        {dataIndex:'material_name',title:'名称',editable:false,},
        {dataIndex:'invstd',title:'包装规格',editable:false,},
        {dataIndex:'invstd2',title:'型号',editable:false,},
        // {dataIndex:'userdefine_id',title:'自定义ID',editable:false,hidden:true,},
        // {dataIndex:'userdefine_name',title:'自定义值',editable:false,},
        {title:'属性',editable:false,
            render:(text,record)=><QueryUserDefine setData={setUserDefine} 
                          objtype={1} dotype={1} id={record.material_id} setRowno={setRowno} rowno={record.rid} />
           },
        {dataIndex:'munit_name',title:'计量单位',editable:false,},
        {dataIndex:'quantity',title:'数量',valueType:'digit',},
    
        {dataIndex:'deliverdate',title:'需求日期',valueType:'date',width:200},
        {dataIndex:'state2',title:'进度',editable:false,hidden:true},
        {dataIndex:'status2',title:'状态',editable:false,hidden:true,},
        {dataIndex:'memo',title:'备注',ellipsis:true,width:200},
        
    ];

   interface DataTypeMain{
        rid?:number,mid?:number,id:number,material_id?:number,material_code?:string,material_name?:string,
        invstd?:string,invstd2?:string,userdefine_id?:string,userdefine_name?:string,munit_name?:string,
        quantity?:number,taxrate?:number,total?:number,netprice?:number,nettotal?:number,price:number,
        deliverdate?:string,state2?:number,status2?:number,memo2?:string,material_addition?:string,
        pic?:string,alloc_type?:number,default_type?:number,
    }

    const columnsMain:ProColumns<DataTypeMain>[]=[
        {dataIndex:'rid',title:'RID',editable:false, },
        {dataIndex:'mid',title:'MID',editable:false, },
        {dataIndex:'id',title:'ID',editable:false, },
        {dataIndex:'material_id',title:'物料ID',editable:false,hidden:true,},
        {dataIndex:'pic',title:'图片' ,editable:false,
           render:(text)=>{
               var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
               return <Image src={pic}  
                      style={{width:100,height:100}} alt='无' />
          },
        },
        {dataIndex:'material_code',title:'SKU编码',editable:false,},
        {dataIndex:'material_name',title:'名称',editable:false,},
        {dataIndex:'invstd',title:'包装规格',editable:false,},
        {dataIndex:'invstd2',title:'型号',editable:false,},
        // {dataIndex:'userdefine_id',title:'自定义ID',editable:false,hidden:true,},
        // {dataIndex:'userdefine_name',title:'自定义值',editable:false,},
        // {title:'属性',editable:false,
        //     render:(text,record)=><QueryUserDefine setData={setUserDefine} 
        //                   objtype={1} dotype={1} id={record.material_id} setRowno={setRowno} rowno={record.rid} />
        //    },
        {dataIndex:'munit_name',title:'计量单位',editable:false,},
        {dataIndex:'quantity',title:'数量',valueType:'digit',editable:false,},
    
        {dataIndex:'deliverdate',title:'需求日期',valueType:'date',width:200,editable:false,},
        // {dataIndex:'state2',title:'进度',editable:false,hidden:true},
        // {dataIndex:'status2',title:'状态',editable:false,hidden:true,},
        {dataIndex:'memo',title:'备注',ellipsis:true,width:300,editable:false,},
        {dataIndex:'default_type',title:'默认类型',valueType:'radio',editable:false,
            valueEnum:{1:{text:'生产'},2:{text:'外购'},3:{text:'委外'}},
        },
        {dataIndex:'alloc_type',title:'分配类型',valueType:'radio',width:200,
            fieldProps:{options:[{value:1,label:'生产'},{value:2,label:'采购'},{value:3,label:'委外'}]}
        },
        
    ];

interface DataTypeDetail{
        rid?:number,mid?:number,id:number,material_id?:number,code?:string,name?:string,
        invstd?:string,invstd2?:string,userdefine_id?:string,userdefine_name?:string,munit_name?:string,
        quantity?:number,taxrate?:number,total?:number,netprice?:number,nettotal?:number,price:number,
        deliverdate?:string,state2?:number,status2?:number,memo2?:string,material_addition?:string,
        pic?:string,alloc_type?:number,default_type?:number,
    }

    const columnsDetail:ProColumns<DataTypeDetail>[]=[
        {dataIndex:'rid',title:'RID',editable:false, },
        {dataIndex:'mid',title:'MID',editable:false, },
        {dataIndex:'id',title:'ID',editable:false, },
        {dataIndex:'material_id',title:'物料ID',editable:false,hidden:true,},
        {dataIndex:'pic',title:'图片' ,editable:false,
           render:(text)=>{
               var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
               return <Image src={pic}  
                      style={{width:100,height:100}} alt='无' />
          },
        },
        {dataIndex:'code',title:'SKU编码',editable:false,},
        {dataIndex:'name',title:'名称',editable:false,},
        {dataIndex:'invstd',title:'包装规格',editable:false,},
        {dataIndex:'invstd2',title:'型号',editable:false,},
        // {dataIndex:'userdefine_id',title:'自定义ID',editable:false,hidden:true,},
        // {dataIndex:'userdefine_name',title:'自定义值',editable:false,},
        // {title:'属性',editable:false,
        //     render:(text,record)=><QueryUserDefine setData={setUserDefine} 
        //                   objtype={1} dotype={1} id={record.material_id} setRowno={setRowno} rowno={record.rid} />
        //    },
        {dataIndex:'munit_name',title:'计量单位',editable:false,},
        {dataIndex:'quantity_require',title:'需求数量',valueType:'digit',editable:false,},
    
        {dataIndex:'deliverdate',title:'需求日期',valueType:'date',width:200,editable:false,},
        // {dataIndex:'state2',title:'进度',editable:false,hidden:true},
        // {dataIndex:'status2',title:'状态',editable:false,hidden:true,},
        // {dataIndex:'memo',title:'备注',ellipsis:true,width:300,editable:false,},
        // {dataIndex:'default_type',title:'默认类型',valueType:'radio',editable:false,
        //     valueEnum:{1:{text:'生产'},2:{text:'外购'},3:{text:'委外'}},
        // },
        // {dataIndex:'alloc_type',title:'分配类型',valueType:'radio',width:200,
        //     fieldProps:{options:[{value:1,label:'生产'},{value:2,label:'采购'},{value:3,label:'委外'}]}
        // },
        
    ];

    function beginAlloc(){
        if(selectedRecord.length==0)
            message.warning('请先选择要分配的备货单');
        else
            {
                 setAtype(1);
                setOpenAlloc(true);
            };
    };

    function exitAlloc(){
        setOpenAlloc(false);
    };

    //保存分配
    async function saveAllocMain(){
        var fdata=editable_allocMain.current?.getRowsData?.();
        // source_mid,source_did,material_id,quantity,deliverdate,alloc_type,
        fdata=fdata?.map((item:any)=>({
               source_mid:item.mid,
               source_did:item.id,
               material_id:item.material_id,
               quantity:item.quantity,
               deliverdate:moment(moment(item.deliverdate).toDate()).format('YYYY-MM-DD HH:mm:ss'),
               alloc_type:item.alloc_type,
               ispart:0,
        }));

        const x=await s_purchase_updateInfo({source:'alloc_purchase_type',x_id:1,operater_id:1,
                        etype:0,fdata});
        if(x.success)
            message.success('分配成功');
        else
            message.warning('保存失败，请联系管理员');
    };


    async function saveAllocDetail(){
       var fdata=editable_allocDetail.current?.getRowsData?.();
       fdata?.map((item:any)=>{
            action_allocDetail.current?.saveEditable?.(item.rid);
        });
        // source_mid,source_did,material_id,quantity,deliverdate,alloc_type,
        fdata=fdata?.map((item:any)=>({
               source_mid:item.mid,
               source_did:item.id,
               material_id:item.material_id,
               quantity:item.quantity_require,
               deliverdate:moment(moment(item.deliverdate).toDate()).format('YYYY-MM-DD HH:mm:ss'),
               alloc_type:2,
               ispart:1,
        }));
        
        // alert(JSON.stringify(fdata));
        
        // source,x_id,operater_id,etype,fdata
        const x=await s_purchase_updateInfo({source:'alloc_purchase_type',x_id:1,operater_id:1,
                        etype:1,fdata});
        if(x.success)
            message.success('子件分配成功');
        else
            message.warning('保存失败，请联系管理员');
    };

 

    //执行分配
    function doAlloc(){
        //  alert(atype);
        //  if(atype==1){
             const fdata=formRef_alloc.current?.getFieldValue('editable_allocMain');
            //  alert(JSON.stringify(fdata));
             fdata.map((item:any)=>{
                  action_allocMain.current?.startEditable(item.rid);
             });
             
        //  }else{
        //      const fdata=editable_allocDetail.current?.getRowsData?.();
        //      fdata?.map((item:any)=>{
        //           action_allocDetail.current?.startEditable(item.rid);
        //      });
        //  };
    };

    //切换到子件时，需刷新为子件未保存分配前
    async function getDetail(key:any){
        setAtype(key);
       if(key==2){
       //  查询原子件分解的记录x_id,cate_id,id,source,fdata
    //    alert(JSON.stringify(selectedRecord[0]));
        const x=await s_getPurchaseInfo({x_id:1, source:'v_purchase_from_saleorder5',
                           fdata:{id:selectedRecord.length>0?selectedRecord[0].id:0}});
        // alert(JSON.stringify(x.data[0]));
        formRef_alloc.current?.setFieldValue('editable_allocDetail',x.data[0]); 
     };
  };

    const tabItems:TabsProps['items']=[
        {
            key:'1',
            label:'主件分配',
            children:<>
                <EditableProTable
                   rowKey='rid'
                   name='editable_allocMain'
                   columns={columnsMain}
                   editableFormRef={editable_allocMain}
                   actionRef={action_allocMain}
                   options={false}
                   search={false}
                   recordCreatorProps={false}
                   editable={{
                      type:'multiple'
                   }}
                   scroll={{y:'65vh'}}
                   /> 
            </>
        },
         {
            key:'2',
            label:'子件分配',
            children:<>
            <EditableProTable
                  rowKey='rid'
                   name='editable_allocDetail'
                   columns={columnsDetail}
                   editableFormRef={editable_allocDetail}
                   actionRef={action_allocDetail}
                   options={false}
                   search={false}
                   recordCreatorProps={false}
                   editable={{
                      type:'multiple'
                   }}
                   scroll={{y:'65vh'}}
                   /> 
            </>
        },
    ];
     
//    主窗体程序=========================================================================================================
    return <>
       <ProCard title='采购分配管理' style={{height:450,overflow:'auto'}}
           extra={<Space>
              {/* <Button onClick={()=>add()}>新增</Button>
              <Button onClick={()=>edit()}>编辑</Button>
              <Button onClick={()=>operateInfo(5)}>审核</Button>
              <Button onClick={()=>operateInfo(6)}>弃审</Button>
              <Button onClick={()=>operateInfo(2)}>冻结</Button>
              <Button onClick={()=>operateInfo(3)}>删除</Button>
              <Button onClick={()=>operateInfo(0)}>恢复</Button> */}
              <Button onClick={()=>beginAlloc()}>开始分配</Button>
           </Space>}
       >
          <ProTable<DataType>
              rowKey='id'
              actionRef={mtable_ref}
              search={false}
              columns={columns}
              scroll={{y:300 }}
              options={false}
              request={async ()=>{
                        // alert(11);
                        const x=await s_getTableInfo({source:'v_sale_order_main5',x_id:1,id:0});
                        // alert(JSON.stringify(x.data));
                        return {
                          data:x.data,
                          success:true,
                        }
                      }}
                      rowSelection={{
                        type:'radio',
                        async onChange(selectedRowKeys, selectedRows, info) {
                            setSelectedRecord(selectedRows);
                            if(selectedRows.length>0){
                                 const id=selectedRows[0].id;
                                 const x=await s_getTableInfoDetail({source:'v_sale_order_detail2',x_id:0,mid:id});
                                 setSelectedDetail( x.data );
                                //  alert(JSON.stringify(x.data));
                            };
                        },
                      }} 
            />
            </ProCard>
            <ProCard style={{height:400,overflow:'auto'}}>
            <ProTable<DataType2>
              options={false}
              rowKey='id'
              // actionRef={mtable_ref}
              search={false}
              columns={columns2}
              scroll={{y:300 }}
              dataSource={selectDetail}
               
            />
       </ProCard>
      

       {/* 采购分配为采购或外购、生产----------------------------------------- */}
        <Modal closable destroyOnClose onCancel={()=>exitAlloc()} onClose={()=>exitAlloc()}
           open={openAlloc}   width={'90%'} style={{top:10}}
           okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
        >
           <ProCard title='采购分配' style={{height:'85vh'}}
              extra={
                <Space>
                    <Button onClick={()=>doAlloc()} hidden={atype==2?true:false}>立即分配</Button>
                    <Button onClick={()=>saveAllocMain()} hidden={atype==2?true:false}>保存主件分配</Button>
                   <Button onClick={()=>saveAllocDetail()} hidden={atype==2?false:true}>保存子件分配</Button>
                  {/*  <Button onClick={()=>saveAlloc()} >完成分配</Button> */}
                </Space>
              }
           >
                <ProForm formRef={formRef_alloc} submitter={false} layout="horizontal" labelAlign="left"
                   initialValues={{
                     editable_allocMain:selectDetail
                   }}
                >
                  <Tabs items={tabItems} onChange={(key:any)=>getDetail(key)} />

                </ProForm>
           </ProCard>

        </Modal>
    </>
};

export default App;